package com.wutianyi.arithmetic.practices;

import java.util.BitSet;

/**
 * @author Administrator 由0和1构成的虫子 http://www.matrix67.com/blog/archives/5063
 */
public class Insects {

	public static void main(String[] args) throws InterruptedException {
		if (null == args) {
			throw new NullPointerException("必须输入0和1构成的虫子串... ...");
		}
		int insectsLen = args[0].length();
		System.out.println("The insects len: " + insectsLen);
		BitSet insects = new BitSet(insectsLen);

		System.out.println("init insects... ...");
		for (int i = 0; i < insectsLen; i++) {
			if (args[0].charAt(i) == '0') {
				insects.set(i, false);
			} else if (args[0].charAt(i) == '1') {
				insects.set(i, true);
			} else {
				throw new IllegalArgumentException("字符串必须有0或1构成... ...");
			}
		}
		printInsects(insects, insectsLen);
		while (!insects.isEmpty()) {
			//经过每次之后，原来的虫子都是严格的增加，所以经过有穷的步骤之后，数据就会变成全部为111111... ...
			boolean rever = true;
			for (int i = insectsLen - 1; i >= 0; i--) {

				if (insects.get(i)) {
					if (rever) {
						insects.set(i, false);
					}
				} else {
					int r = (int) (Math.random() * Integer.MAX_VALUE);
					if (r % 2 == 0) {
						insects.set(i, false);
					} else {
						insects.set(i, true);
						rever = false;
					}
				}
			}
			printInsects(insects, insectsLen);
			Thread.sleep(500);
		}
		// System.out.println(insects.length());
		// System.out.println(insects.size());
		printInsects(insects, insectsLen);
	}

	private static void printInsects(BitSet insects, int len) {
		System.out.print("虫子： ");
		for (int i = 0; i < len; i++) {
			if (insects.get(i)) {
				System.out.print('1');
			} else {
				System.out.print('0');
			}
		}
		System.out.println();
	}
}
